package org.vectrics.logging;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.Logger;
import org.apache.log4j.Priority;
import org.apache.log4j.spi.LoggingEvent;



public class NotifyAppender extends AppenderSkeleton {
	private Collection handlers = new HashSet();
	private static NotifyAppender instance = null;

	
	public NotifyAppender() {
		super();
	}
	
	public static NotifyAppender getInstance() {
		if (instance == null) {
			instance = new NotifyAppender();
			Logger.getRootLogger().addAppender(instance);
		}
		
		return(instance);
	}
	
	public NotifyAppenderHandler findHandler(String id) {
		NotifyAppenderHandler foundHandler = null;
		Iterator iter = this.handlers.iterator();
		while ((iter.hasNext()) && (foundHandler == null)) {
			NotifyAppenderHandler handler = (NotifyAppenderHandler)iter.next();
			if (handler.getId().equals(id)) {
				foundHandler = handler;
			}
		}
		return(foundHandler);
	}
	
	public void addHandler(NotifyAppenderHandler handler) {
		Logger.getLogger("org.vectrics.logging.NotifyAppender").info("addHandler() called");
		NotifyAppenderHandler sameHandler = this.findHandler(handler.getId());
		if (sameHandler == null) {
			this.handlers.add(handler);
		} else {
			Logger.getLogger("org.vectrics.logging.NotifyAppender").info("addHandler() - handler already found, not added");
		}
		Logger.getLogger("org.vectrics.logging.NotifyAppender").info("addHandler() - now has " + this.handlers.size() + " handlers.");
	}
	
	/**
	 * @return Returns the handlers.
	 */
	public Collection getHandlers() {
		return handlers;
	}

	/**
	 * @param handlers The handlers to set.
	 */
	public void setHandlers(Collection handlers) {
		this.handlers = handlers;
	}

	protected void append(LoggingEvent loggingEvent) {
		if (loggingEvent.getLevel().isGreaterOrEqual(Priority.ERROR)) {
			if (this.handlers.size() > 0) {
				Iterator iter = this.handlers.iterator();
				while (iter.hasNext()) {
					NotifyAppenderHandler handler = (NotifyAppenderHandler)iter.next();
					handler.handleEvent(loggingEvent);
				}
			}
		}
	}

	public void close() {
	}

	public boolean requiresLayout() {
		return false;
	}

}
